package command

import (
	"encoding/base64"
	"fmt"
	"gitee.com/csingo/cContext"
	"gitee.com/csingo/cHelper"
	"gitee.com/csingo/cLog"
	"io/ioutil"
	"os/user"
	"path/filepath"
	"satis-go/config/vars"
)

type InitDeployKeyCommand struct{}

func (i *InitDeployKeyCommand) CommandName() (app, name string) {
	return "collector", "InitDeployKeyCommand"
}

func (i *InitDeployKeyCommand) Handle() {
	ctx := cContext.New()
	if !vars.CollectorConfig.Enable {
		return
	}
	user, err := user.Current()
	if err != nil {
		cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:获取系统用户异常")
		return
	}

	sshPath := filepath.Clean(fmt.Sprintf("%s/.ssh", user.HomeDir))
	err = cHelper.MkDirAll(sshPath, 0755)
	if err != nil {
		cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:生成ssh目录异常")
		return
	}

	privatePath := filepath.Clean(fmt.Sprintf("%s/id_rsa", sshPath))
	publicPath := filepath.Clean(fmt.Sprintf("%s/id_rsa.pub", sshPath))

	if vars.CollectorConfig.PrivateKey != "" {
		prikey, err := base64.StdEncoding.DecodeString(vars.CollectorConfig.PrivateKey)
		prikey = []byte(string(prikey) + "\n")
		if err != nil {
			cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:base64解码失败")
			return
		}
		err = ioutil.WriteFile(privatePath, prikey, 0600)
		if err != nil {
			cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:写入私钥异常")
			return
		}
	}

	if vars.CollectorConfig.PublicKey != "" {
		pubkey, err := base64.StdEncoding.DecodeString(vars.CollectorConfig.PublicKey)
		if err != nil {
			cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:base64解码失败")
			return
		}
		err = ioutil.WriteFile(publicPath, pubkey, 0600)
		if err != nil {
			cLog.WithContext(ctx, nil).Panic("InitDeployKeyCommand.Handle:写入公钥异常")
			return
		}
	}
	priKeyContentByte, _ := ioutil.ReadFile(privatePath)
	pubKeyContentByte, _ := ioutil.ReadFile(publicPath)

	cLog.WithContext(ctx, map[string]interface{}{
		"config":  vars.CollectorConfig,
		"public":  string(pubKeyContentByte),
		"private": string(priKeyContentByte),
	}).Debug("InitDeployKeyCommand.Handle:检查sshkey是否正常")
}
